package com.bjtang.book.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bjtang.book.dto.LoginDto;
import com.bjtang.book.dto.LogonDto;
import com.bjtang.book.dto.ReturnDto;
import com.bjtang.book.entiy.SysUser;
import com.bjtang.book.enums.SESSION;
import com.bjtang.book.service.SysUserService;
import com.bjtang.book.util.ApplicationUtils;
import com.bjtang.book.util.MailClientSend;
import com.bjtang.book.util.RSA加密;
import com.bjtang.book.util.ReturnUtil;
import com.bjtang.book.util.验证码生成器;
import com.bjtang.book.util.验证码生成器2;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "认证管理")
@Validated
@RestController
@RequestMapping(value = "/login/")
public class LoginController {
	@Autowired
	SysUserService sysUserService;

	@ApiOperation("登录_验证码")
	@GetMapping("/")
	public void dengluyzm(HttpServletRequest request, HttpServletResponse response) throws IOException {
		验证码生成器2 vc = new 验证码生成器2();
		// 获取图片对象
		BufferedImage bi = vc.generateCode();
		// 获得图片的文本内容
		String yzm = vc.getText();
		// 将系统生成的文本内容保存到session中
		request.getSession().setAttribute("YZM", yzm);
		// 设置返回类型
		response.setContentType("image/jpeg");
		// 向浏览器输出图片
		验证码生成器2.output(bi, response.getOutputStream());
	}

	@ApiOperation("登录方法")
	@PostMapping("/")
	public ReturnDto login(@RequestBody @Valid LoginDto loginDto) {
		if (ApplicationUtils.getRequest().getSession().getAttribute("YZM") == null) {
			return ReturnUtil.error(402, "登录失败!没有验证码生成");
		}
		String yzm = ApplicationUtils.getRequest().getSession().getAttribute("YZM").toString();
		if (!yzm.equalsIgnoreCase(loginDto.getYzm())) {
			return ReturnUtil.error(402, "登录失败!验证码错误");
		}
		SysUser one = sysUserService.lambdaQuery().eq(SysUser::getLoginName, loginDto.getLoginName())
				.eq(SysUser::getPassword, new RSA加密().加密(loginDto.getPassword())).one();
		if (one != null) {
			// 插入用户ID到session中
			ApplicationUtils.getRequest().getSession().setAttribute(SESSION.USER_ID_SESSION.name(), one.getUserId());
			// List<SysMenu> myselfMenus = myService.getMyselfMenus();
			// 插入用户权限列表到session中
			// ApplicationUtils.getRequest().getSession().setAttribute(SESSION.USER_MENUS_SESSION.name(),
			// myselfMenus);
			// System.err.println("登录成功");
			return ReturnUtil.success();
		} else {
			return ReturnUtil.error(403, "登录失败!用户名或密码错误");
		}
	}

	@ApiOperation("注册_验证码")
	@GetMapping("/logon/{email}")
	public ReturnDto logonyzm(HttpServletRequest request, @PathVariable @Email String email) throws Exception {
		String yzm = 验证码生成器.getText();
		// System.err.println(yzm);
		// 发送邮件
		MailClientSend.putMessage(email, yzm);

		// 将系统生成的文本内容保存到session中
		request.getSession().setAttribute("LOGONYZM", yzm);
		return ReturnUtil.success();
	}

	@ApiOperation("注册方法")
	@PostMapping("/logon/")
	public ReturnDto logon(@RequestBody @Valid LogonDto logonDto) {
		if (ApplicationUtils.getRequest().getSession().getAttribute("LOGONYZM") == null) {
			return ReturnUtil.error(402, "注册失败!没有验证码生成");
		}
		String yzm = ApplicationUtils.getRequest().getSession().getAttribute("LOGONYZM").toString();
		if (!yzm.equalsIgnoreCase(logonDto.getYzm())) {
			return ReturnUtil.error(402, "注册失败!验证码错误");
		}
		List<SysUser> list = sysUserService.lambdaQuery().eq(SysUser::getLoginName, logonDto.getLoginName()).list();
		if (list.size() != 0)
			return ReturnUtil.error(402, "注册失败!登录名已被使用");

		return ReturnUtil.successOrError(sysUserService.save(logonDto.getUser()), logonDto.getUser().getName());
	}

	@ApiOperation("登出方法")
	@DeleteMapping("/")
	public ReturnDto logout() {
		ApplicationUtils.getRequest().getSession().invalidate();
		return ReturnUtil.success();
	}

}
